import * as React from 'react';
import _ from 'lodash'
import { connect } from 'react-redux'
import { Dispatch, bindActionCreators } from 'redux'
import { RootState } from 'src/redux'
//ui
import { Card } from "antd"
//ds
import { WordSentenceState } from './reducer';
import * as  Action from './reducer'
//redux ds
import WordSentenceIndex from './components';
import { useEffect } from 'react';
import { MainInfoState } from '../MainInfo/reducer';
import WordSentenceIndexAdd from './components/Add';

export interface WordSentenceListProps {
    state: WordSentenceState;
    fetch: typeof Action.fetchBySourceAndWord;
    fetchBySource: typeof Action.fetchBySource;
    mainInfoState: MainInfoState
}

const _WordSentence: React.SFC<WordSentenceListProps> = (props) => {
    const { mainInfoState, fetch, fetchBySource } = props
    useEffect(() => {
        if (mainInfoState.wordSourceId && mainInfoState.word === '' && mainInfoState.wordSourceId !== -1)
            fetchBySource(mainInfoState.wordSourceId)
        if (mainInfoState.wordSourceId && !_.isNull(mainInfoState.word) && mainInfoState.wordSourceId !== -1)
            fetch(mainInfoState.wordSourceId, mainInfoState.word)
    }, [fetch, fetchBySource, mainInfoState.word, mainInfoState.wordSourceId])

    let sentenceList = (<div>请选择单词</div>)
    if (!_.isNull(mainInfoState.word))
        sentenceList = (
            <div>
                {props.state.dto.dtos.map((_, index) =>
                    <WordSentenceIndex index={index} />
                )}
                <WordSentenceIndexAdd  />
            </div>
        )
    return (
        <Card
            size='small'
            title='单词例句'
            className='csc50'
        >
            {sentenceList}
        </Card>
    );
}

const mapStateToProps = (state: RootState) => ({
    state: state.WordSentenceState,
    mainInfoState: state.MainInfoState
})

const mapDispatchToProps = (dispatch: Dispatch) => bindActionCreators({
    fetch: Action.fetchBySourceAndWord,
    fetchBySource: Action.fetchBySource,
}, dispatch);

/**
 * 得到当前过滤器并渲染 Link。
 */
const WordSentence = connect(
    mapStateToProps,
    mapDispatchToProps
)(_WordSentence)

export default WordSentence